﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Enter.Mvc.Base.Infrastructure.ActionFilters;

namespace Enter.Mvc.Base.Infrastructure
{
	public class UnityControllerActionInvoker : ControllerActionInvoker
	{
	   private readonly IActionFilterRegistry registry;

	   public UnityControllerActionInvoker(IActionFilterRegistry registry)
        {
            this.registry = registry;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="actionDescriptor"></param>
        /// <param name="actionReturnValue"> actionReturnValue </param>
        /// <returns></returns>
       protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
       {
               if (actionReturnValue == null)
               {
                   // controllerContext.Controller.ViewData.Model = new OxiteModel { Container = new NotFoundPageContainer() };
				   //return new EmptyResult();
               }
			   if (actionReturnValue is ActionResult)
			   {
				   if (actionReturnValue is ViewResult)
				   {
					   return actionReturnValue as ViewResult;
				   }
				   return actionReturnValue as ActionResult;
			   }
			   else
			   {
				   controllerContext.Controller.ViewData.Model = actionReturnValue;
				   return new ViewResult { ViewData = controllerContext.Controller.ViewData, TempData = controllerContext.Controller.TempData };
			   }
	   }
       
		protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            FilterInfo baseFilters = base.GetFilters(controllerContext, actionDescriptor);

            FilterInfo registeredFilters = registry.GetFilters(new ActionFilterRegistryContext(controllerContext, actionDescriptor));

			int count = baseFilters.ActionFilters.Count;

            foreach (IActionFilter actionFilter in registeredFilters.ActionFilters)
				baseFilters.ActionFilters.Insert(count, actionFilter);
            foreach (IAuthorizationFilter authorizationFilter in registeredFilters.AuthorizationFilters)
                baseFilters.AuthorizationFilters.Add(authorizationFilter);
            foreach (IExceptionFilter exceptionFilter in registeredFilters.ExceptionFilters)
                baseFilters.ExceptionFilters.Add(exceptionFilter);
            foreach (IResultFilter resultFilter in registeredFilters.ResultFilters)
                baseFilters.ResultFilters.Add(resultFilter);

            return baseFilters;
        }
   
	}
}
